#! /usr/bin/python
# -*- coding: utf-8 -*-

from google.appengine.ext import db

#Model for relation from Paper to ADvertisement-Ebook
#multiple-to-multiple mapping 

#error info definition:
EBOOKMAPPING_ERROR_CODE_SUCCESS = 0
EBOOKMAPPING_ERROR_CODE_LOSE_PARAMS = 1
EBOOKMAPPING_ERROR_CODE_NOT_VALID_PID = 2
EBOOKMAPPING_ERROR_CODE_NOT_VALID_EBID = 3
EBOOKMAPPING_ERROR_CODE_NOT_VALID_PRIORITY = 4
EBOOKMAPPING_ERROR_CODE_NO_CORRESPONDING_PAPER = 5
EBOOKMAPPING_ERROR_CODE_NO_CORRESPONDING_EBOOK = 6
EBOOKMAPPING_ERROR_CODE_EXIST_MAPPING = 7
EBOOKMAPPING_ERROR_CODE_NOEXIST_MAPPING = 8

EBOOKMAPPING_ERROR_MESSAGES = [
    '成功',
    '缺少参数，必需同时指定pid+ebid+priority',
    '无效的pid参数',
    '无效的ebid参数',
    '无效的优先级参数',
    '没有对应的文章',
    '没有对应的电子书',
    '该映射已经存在',
    '该映射不存在'
    ]


#同一篇文章的推荐书按priority排序
class PaperBookMapping(db.Model):
    id = db.IntegerProperty()
    pid = db.IntegerProperty()
    ebid = db.IntegerProperty()
    priority = db.IntegerProperty()


#Return the PaperBookMapping DB Model
def readPaperBookMapping(id):
    q = db.GqlQuery("SELECT * FROM PaperBookMapping WHERE id = :id", id=id)
    mappingModel = q.get()
    return mappingModel

def readPaperBookMappingBy2Ids(pid, ebid):
    q = db.GqlQuery("SELECT * FROM PaperBookMapping WHERE pid = :pid and ebid = :ebid", pid=pid, ebid=ebid)
    mappingModel = q.get()
    return mappingModel

def writePaperBookMapping(mappingModel):
    mappingModel.put()

def deletePaperBookMapping(mappingModel):
    mappingModel.delete()

def listAdebooksByPaper(pid, offset=0, limit=5):
    gplQuery = db.GqlQuery("SELECT * FROM PaperBookMapping WHERE pid = :pid ORDER BY priority DESC", pid=pid)
    resultList = gplQuery.fetch(limit, offset)
    return resultList

def listAllAdebooks(offset=0, limit=100):
    gplQuery = db.GqlQuery("SELECT * FROM PaperBookMapping ORDER BY pid DESC")
    resultList = gplQuery.fetch(limit, offset)
    return resultList
